<template>
  <div class="employee-table-container">
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      max-height="450"
      ref="tableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="name" label="姓名" width="100" />
      <el-table-column fixed prop="salary" label="岗位工资" width="100" />
      <el-table-column prop="post_level" label="岗位档级" width="100" />
      <el-table-column prop="birthday" label="生日" width="120" />
      <el-table-column prop="tel" label="手机号" width="120" />
      <el-table-column prop="IDnumber" label="身份证号" width="180" />
      <el-table-column prop="itemName" label="项目名称" width="150" />
      <el-table-column prop="companyName" label="公司名称" width="150" />
      <el-table-column prop="politics_status" label="政治面貌" width="100" />
      <el-table-column prop="native_place" label="籍贯" width="100" />
      <el-table-column prop="education" label="学历" width="80" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="staff_status" label="员工状态" width="100" />
      <el-table-column prop="employment" label="用工形式" width="100" />
      <el-table-column prop="entry_time" label="入职时间" width="120" />
      <el-table-column prop="time_section" label="合同区间" width="160" />
      <el-table-column prop="leave_time" label="离职时间" width="120" />
      <el-table-column prop="contract_duration" label="合同期限" width="100" />
      <el-table-column prop="bank_account" label="银行卡号" width="180" />
      <el-table-column prop="bank_name" label="开户行" width="120" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button 
            link 
            type="danger" 
            size="small" 
            @click="deleteRow(scope.row)"
            :disabled="loadingIds.includes(scope.row.id)"
          >
            <i class="el-icon-delete" /> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="button-group mt-3">
      <el-button 
        type="primary" 
        size="small" 
        @click="onAddItem"
        :disabled="isAdding"
      >
        <i class="el-icon-plus" /> 添加员工
      </el-button>
      
      <el-button 
        type="success" 
        size="small" 
        class="ml-2"
        @click="toggleSelection()"
        :disabled="tableData.length === 0"
      >
        <i class="el-icon-check" /> 全选/取消
      </el-button>
      
      <el-button 
        type="danger" 
        size="small" 
        class="ml-2"
        @click="batchDelete"
        :disabled="selectedRows.length === 0"
      >
        <i class="el-icon-delete" /> 批量删除
      </el-button>
      
      <el-button 
        type="info" 
        size="small" 
        class="ml-2"
        @click="showMessageBox"
      >
        <i class="el-icon-info" /> 显示示例对话框
      </el-button>
    </div>
    
    <!-- 状态提示 -->
    <el-alert 
      title="提示：可通过表格上方的选择框选中多行进行批量操作" 
      type="info" 
      :closable="false"
      class="mt-3"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, nextTick } from 'vue'
import dayjs from 'dayjs'
import { ElTable, ElMessageBox, ElMessage } from 'element-plus'

// 员工信息类型定义
interface Employee {
  id: number;
  name: string;
  salary: number;
  post_level: string;
  birthday: string;
  tel: string;
  IDnumber: string;
  itemName: string;
  companyName: string;
  politics_status: string;
  native_place: string;
  education: string;
  createTime: string;
  staff_status: string;
  employment: string;
  entry_time: string;
  time_section: string;
  leave_time: string;
  contract_duration: string;
  bank_account: string;
  bank_name: string;
}

// 表格引用
const tableRef = ref<InstanceType<typeof ElTable>>()

// 状态管理
const state = reactive({
  tableData: [] as Employee[],
  selectedRows: [] as Employee[],
  isAdding: false,
  loadingIds: [] as number[]
})

// 解构状态以便在模板中使用
const { tableData, selectedRows, isAdding, loadingIds } = toRefs(state)

// 模拟数据
const generateMockData = (count: number = 5): Employee[] => {
  const result: Employee[] = []
  for (let i = 1; i <= count; i++) {
    result.push({
      id: i,
      name: `员工${i}`,
      salary: 5000 + i * 100,
      post_level: `P${i % 5 + 1}`,
      birthday: dayjs().subtract(20 + i, 'year').format('YYYY-MM-DD'),
      tel: `1380013800${i}`,
      IDnumber: `110101199${i}0101000${i}`,
      itemName: `项目${i % 3 + 1}`,
      companyName: `公司${i % 2 + 1}`,
      politics_status: ['党员', '团员', '群众'][i % 3],
      native_place: ['北京', '上海', '广州', '深圳'][i % 4],
      education: ['本科', '硕士', '博士'][i % 3],
      createTime: dayjs().subtract(i, 'day').format('YYYY-MM-DD HH:mm:ss'),
      staff_status: ['在职', '离职'][i % 2],
      employment: ['全职', '兼职', '实习'][i % 3],
      entry_time: dayjs().subtract(i + 1, 'year').format('YYYY-MM-DD'),
      time_section: `${dayjs().subtract(i, 'year').format('YYYY-MM-DD')} 至 ${dayjs().add(1, 'year').format('YYYY-MM-DD')}`,
      leave_time: i % 2 === 0 ? '' : dayjs().subtract(i - 1, 'month').format('YYYY-MM-DD'),
      contract_duration: ['1年', '2年', '3年', '5年'][i % 4],
      bank_account: `622202020000000${i.toString().padStart(3, '0')}`,
      bank_name: ['工商银行', '建设银行', '农业银行', '中国银行'][i % 4]
    })
  }
  return result
}

// 初始化表格数据
tableData.value = generateMockData()

// 处理选择变化
const handleSelectionChange = (val: Employee[]) => {
  selectedRows.value = val
}

// 切换选择状态
const toggleSelection = (rows?: Employee[]) => {
  nextTick(() => {
    if (rows) {
      rows.forEach(row => {
        tableRef.value?.toggleRowSelection(row)
      })
    } else {
      // 如果没有参数，则切换全选/取消全选
      const isAllSelected = selectedRows.value.length === tableData.value.length
      tableData.value.forEach(row => {
        tableRef.value?.toggleRowSelection(row, !isAllSelected)
      })
    }
  })
}

// 删除单行
const deleteRow = async (row: Employee) => {
  const index = tableData.value.findIndex(item => item.id === row.id)
  if (index === -1) return
  
  // 确认删除
  try {
    await ElMessageBox.confirm('确定要删除该员工信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 显示加载状态
    loadingIds.value.push(row.id)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 删除数据
    tableData.value.splice(index, 1)
    
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  } finally {
    // 隐藏加载状态
    loadingIds.value = loadingIds.value.filter(id => id !== row.id)
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的员工')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条员工信息吗？`, 
      '提示', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 显示加载状态
    const selectedIds = selectedRows.value.map(row => row.id)
    selectedIds.forEach(id => {
      if (!loadingIds.value.includes(id)) {
        loadingIds.value.push(id)
      }
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 删除数据
    tableData.value = tableData.value.filter(
      row => !selectedIds.includes(row.id)
    )
    
    // 清空选择
    selectedRows.value = []
    
    ElMessage.success(`成功删除 ${selectedIds.length} 条数据`)
  } catch (error) {
    ElMessage.info('已取消删除')
  } finally {
    // 隐藏加载状态
    selectedIds.forEach(id => {
      loadingIds.value = loadingIds.value.filter(loadingId => loadingId !== id)
    })
  }
}

// 添加新项目
const onAddItem = async () => {
  try {
    isAdding.value = true
    
    // 生成新ID
    const maxId = tableData.value.length > 0 
      ? Math.max(...tableData.value.map(item => item.id)) 
      : 0
    
    // 创建新员工对象
    const newEmployee: Employee = {
      id: maxId + 1,
      name: '新员工',
      salary: 5000,
      post_level: 'P1',
      birthday: dayjs().subtract(25, 'year').format('YYYY-MM-DD'),
      tel: '13800138000',
      IDnumber: '110101199001010000',
      itemName: '项目1',
      companyName: '公司1',
      politics_status: '群众',
      native_place: '北京',
      education: '本科',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      staff_status: '在职',
      employment: '全职',
      entry_time: dayjs().format('YYYY-MM-DD'),
      time_section: `${dayjs().format('YYYY-MM-DD')} 至 ${dayjs().add(1, 'year').format('YYYY-MM-DD')}`,
      leave_time: '',
      contract_duration: '1年',
      bank_account: '622202020000000000',
      bank_name: '工商银行'
    }
    
    // 添加到表格
    tableData.value.unshift(newEmployee)
    
    // 选中新添加的行
    nextTick(() => {
      tableRef.value?.toggleRowSelection(newEmployee, false)
    })
    
    ElMessage.success('添加成功')
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    isAdding.value = false
  }
}

// 显示示例消息框
const showMessageBox = () => {
  ElMessageBox.confirm(
    '此操作将永久删除选中文件，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      distinguishCancelAndClose: true
    }
  )
    .then(() => {
      ElMessage.success('删除完成')
    })
    .catch((action) => {
      if (action === 'cancel') {
        ElMessage.info('已取消删除')
      } else if (action === 'close') {
        ElMessage.info('对话框已关闭')
      }
    })
}
</script>

<style scoped>
.employee-table-container {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 优化表格列宽和样式 */
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>    